﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetfractionHub.Network.Protocol.BASE.Handler
{
    public class HandlerRES : ProtocolMessageActionHandler
    {
        public HandlerRES()
            : base()
        {
            ParameterCodes = new List<string>(new string[] { "FN", "SI", "SL", "TO" });

            mSupportedConnectionStates = new List<RemoteMachine.ConnectionState>();
        }

        #region ProtocolMessageActionHandler Members

        public override string ProtocolActionCode
        {
            get { return "RES"; }
        }

        public override bool HandleProtocolMessage(NetfractionHub.RemoteMachine.Node node, ProtocolMessage message, IEnumerable<ProtocolFeature> extenders)
        {
            if (message.Parameters.Count != 0)
            {
                message.Parameters = DecodeParameters(message.Parameters);
                //(node as RemoteMachine.Hub).SessionId = message.GETParameterOptions[0].ParameterValue;

                // should check for TCP Active...

                if (node.Connection.State != RemoteMachine.ConnectionState.Normal)
                {
                    // invalid state
                    return false;
                }

                if (message.MessageType == ProtocolMessage.MessageTypeEnum.Direct || message.MessageType == ProtocolMessage.MessageTypeEnum.Echo)
                {
                    if (message.SessionId != node.SessionId)
                    {
                        return false;
                    }

                    RemoteMachine.Node targetNode = ConnectionManager.GetNodeBySessionId(message.TargetSessionId);
                    if (targetNode != null)
                    {
                        ConnectionManager.SendSearchResultToRequestingNode(node, targetNode, message);
                    }
                    else
                    {
                        // targetNode doesn't exist or is no longer connected to the hub
                    }
                }

                return true;
            }
            return false;
        }

        #endregion
    }
}
